package com.woniuxy.sales.controller;

import com.woniuxy.sales.model.vo.FavoritesVo;
import com.woniuxy.sales.service.FavoritesService;
import com.woniuxy.sales.untils.JwtTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.util.List;


@RestController
@RequestMapping("/favorites")
@Api(tags = "收藏夹接口")
@Slf4j
public class FavoritesController {

    @Autowired
    private FavoritesService favoritesService;
    @Autowired
    private JwtTemplate jwtTemplate;

    @GetMapping("/query")
    @ApiOperation("查询收藏夹")
    public ResponseEntity<List<FavoritesVo>> query(
            @RequestHeader(name = "Authorization", required = false) String token) {
        //从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        log.info("用户id:{}", userId);
        //调用业务层查询订单
        List<FavoritesVo> favoritesVos = favoritesService.query(userId);
        log.info("收藏夹信息:{}", favoritesVos);
        return ResponseEntity.ok(favoritesVos);
    }


    @PostMapping("/add/{productId}")
    @ApiOperation("添加收藏")
    public ResponseEntity add(
            @RequestHeader(name = "Authorization", required = false) String token,
            @PathVariable Integer productId) {
        // 从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        try {
            favoritesService.add(userId, productId);
            return ResponseEntity.ok().build();
        } catch (RuntimeException e) {
            // 返回错误消息
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }


    @PostMapping("/remove/{productId}")
    @ApiOperation("删除收藏")
    public ResponseEntity remove(
            @RequestHeader(name = "Authorization", required = false) String token,
            @PathVariable Integer productId) {
        //从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        //调用业务层创建订单
        favoritesService.remove(userId, productId);
        return ResponseEntity.ok().build();
    }



    


}